package com.fuang.multithread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * Created by Fuang on 2018-9-27.
 */
public class ThreadTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // FutureTask
        FutureTask<String> futureTask = new FutureTask<String>(new CallTask());
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(futureTask);
        System.out.println("do other thing!");
        System.out.println("call back = " + futureTask.get());

        // Future
        Future<String> future = executor.submit(new CallTask());
        System.out.println("do other thing!");
        System.out.println("call2 back = " + future.get());

        // Runnable
        futureTask = new FutureTask<String>(new RunTask(), "run succ");
        executor.execute(futureTask);
        System.out.println("do other thing!");
        System.out.println("run back = " + futureTask.get());
    }

    static class RunTask implements Runnable {

        @Override
        public void run() {
            System.out.println("run start : " + System.currentTimeMillis());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("run end : " +System.currentTimeMillis());
        }
    }

    static class CallTask implements Callable<String> {

        @Override
        public String call() throws Exception {
            System.out.println("call start : " + System.currentTimeMillis());
            Thread.sleep(1000);
            System.out.println("call end : " +System.currentTimeMillis());
            return "call succ";
        }
    }
}
